import pygame,sys,time,random
from pygame.locals import *

# 定义main函数
def main():
    #定义每秒执行循环的次数
    executeTimes = pygame.time.Clock()
    # 创建pygame窗口
    screen = pygame.display.set_mode((640,480))
    pygame.display.set_caption('无敌不死炫彩贪吃蛇')


    # 舌头的位置
    snakeHeader = [400,400]
    #蛇身三个方块的位置
    snakeBody = [[400,400],[420,400],[440,400]]
    #设置默认蛇身颜色
    snakeBodyColor=[[0,221,255],[255,115,0],[255,0,200]]
    #食物的初始位置
    foodPosition = [200,200]
    #默认的运动方向
    direction = 'left'
    #食物颜色，默认白色
    foodColor=[255,255,255]
    while True:
        #绘制背景
        screen.fill([0,0,0])
        # 检测例如按键等pygame事件
        for event in pygame.event.get():
            if event.type == QUIT:
                exit()
            elif event.type == KEYDOWN:
                # 判断键盘事件
                if event.key == K_RIGHT:
                    direction = 'right'
                if event.key == K_LEFT:
                    direction = 'left'
                if event.key == K_UP:
                    direction = 'up'
                if event.key == K_DOWN:
                    direction = 'down'
        # 根据方向移动蛇头的坐标
        if direction == 'right':
            snakeHeader[0] += 20
        if direction == 'left':
            snakeHeader[0] -= 20
        if direction == 'up':
            snakeHeader[1] -= 20
        if direction == 'down':
            snakeHeader[1] += 20
        # 蛇头和食物重复，则为吃掉
        if snakeHeader[0] == foodPosition[0] and snakeHeader[1] == foodPosition[1]:
            #增加蛇身
            snakeBody.insert(0,list(snakeHeader))
            #将食物的颜色追加到蛇身上
            snakeBodyColor.insert(0,foodColor)
            #重新生成食物下标
            x = random.randrange(1,32)
            y = random.randrange(1,24)
            foodPosition = [int(x*20),int(y*20)]
            #生成新的食物颜色
            foodColor=[random.randrange(1,256),random.randrange(1,256),random.randrange(1,256)]
        else:
            #增加蛇身，移除蛇尾
            snakeBody.insert(0,list(snakeHeader))
            snakeBody.pop()

        for i in range(len(snakeBody)):
            position=snakeBody[i]
            pygame.draw.circle(screen,snakeBodyColor[i],(position[0],position[1]),10)
            pygame.draw.circle(screen,foodColor,(foodPosition[0],foodPosition[1]),10)

        # 刷新pygame显示层
        pygame.display.update()
        #x,y轴超出，归位
        if snakeHeader[0] > 620 or snakeHeader[0] < 0 or snakeHeader[1]>480 or snakeHeader[1]<0:
            snakeHeader = [400,400]
            snakeBody = [[400,400],[420,400],[440,400]]
        # 每秒执行循环5次，保持蛇持续走动，增加X
        executeTimes.tick(4)

if __name__ == "__main__":
    main()